from django.db import connection, transaction
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

class DB(object):

    def query(self, sql):
        cursor = connection.cursor()
        count=cursor.execute(sql,None)
        rows=cursor.fetchall()
        col_names = [desc[0] for desc in cursor.description]
        rows=[
        dict(zip(col_names, row))
        for row in rows
        ]
        return count, rows

    def queryOne(self, sql):
        cursor = connection.cursor()
        count=cursor.execute(sql,None)
        row=cursor.fetchone()
        col_names = [desc[0] for desc in cursor.description]
        row = dict(zip(col_names, row))
        return row


    def execute(self, sql):
        cursor = connection.cursor()
        count=cursor.execute(sql,None)
        transaction.commit_unless_managed()
        return count

class Data:
    db = None

def getDB():
    if Data.db==None:
        Data.db=DB()
    return Data.db
    #return DB("127.0.0.1", "root", "123456", 3306, "liuhua")
    # import tools.DB_Driver as DB
    # db = DB.getDB()